package com.naodong.shenluntiku.mvp.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.widget.TextView;

import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.naodong.shenluntiku.R;
import com.naodong.shenluntiku.di.component.DaggerLoginComponent;
import com.naodong.shenluntiku.di.module.LoginModule;
import com.naodong.shenluntiku.di.module.SafeVerModule;
import com.naodong.shenluntiku.di.module.VerCodeModule;
import com.naodong.shenluntiku.mvp.contract.LoginContract;
import com.naodong.shenluntiku.mvp.contract.SafeVerContract;
import com.naodong.shenluntiku.mvp.contract.VerCodeContract;
import com.naodong.shenluntiku.mvp.model.bean.EventBusTag;
import com.naodong.shenluntiku.mvp.model.bean.IdAndCon;
import com.naodong.shenluntiku.mvp.model.bean.LoginInfo;
import com.naodong.shenluntiku.mvp.model.bean.LoginVerInfo;
import com.naodong.shenluntiku.mvp.model.bean.ResponseMsg;
import com.naodong.shenluntiku.mvp.model.bean.VerCode;
import com.naodong.shenluntiku.mvp.presenter.LoginPresenter;
import com.naodong.shenluntiku.mvp.presenter.SafeVerPresenter;
import com.naodong.shenluntiku.mvp.presenter.VerCodePresenter;
import com.naodong.shenluntiku.mvp.view.widget.CodeInputView;
import com.naodong.shenluntiku.util.MD5;
import com.squareup.phrase.Phrase;
import com.yatatsu.autobundle.AutoBundleField;

import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.CompositeDisposable;
import me.shingohu.man.base.BaseMVPActivity;
import me.shingohu.man.di.component.AppComponent;
import me.shingohu.man.intergation.EventManager;
import me.shingohu.man.util.RxUtils;
import me.shingohu.man.util.ToastUtil;

/**
 * Created by hujie on 17/5/25.
 */

public class InputVerCodeActivity extends BaseMVPActivity<LoginPresenter> implements VerCodeContract.View, LoginContract.View, SafeVerContract.View {

    @BindView(R.id.codeInputView)
    CodeInputView codeInputView;

    @BindView(R.id.regetTV)
    TextView regetTV;

    CompositeDisposable disposable = new CompositeDisposable();
    @BindView(R.id.phoneTV)
    TextView phoneTV;

    @AutoBundleField
    String phone;
    @AutoBundleField
    VerCode verCode;

    @Inject
    VerCodePresenter verCodePresenter;
    @Inject
    SafeVerPresenter safeVerPresenter;


    @Override
    protected void onCreateInit(Bundle savedInstanceState) {
        KeyboardUtils.showSoftInput(codeInputView);
        countDown();
        codeInputView.setInputCompleteListener(code -> {

            String md5 = MD5.md5(MD5.md5(code));
            if (md5.equals(verCode.getPhoneCode())) {
                requestLogin(code);
            }else{
                ToastUtil.makeToast("验证码不正确,请重新输入");
                codeInputView.clear();
            }
        });
        phoneTV.setText(phone);



    }

    private void requestLogin(String code) {

        String deviceNum = DeviceUtils.getAndroidID();
        String deviceName = DeviceUtils.getManufacturer() + " " + DeviceUtils.getModel();
        mPresenter.requestLogin(phone, code, deviceNum, deviceName);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {


        DaggerLoginComponent
                .builder()
                .appComponent(appComponent)
                .loginModule(new LoginModule(this)) //请将LoginModule()第一个首字母改为小写
                .verCodeModule(new VerCodeModule(this)) //请将VerCodeModule()第一个首字母改为小写
                .safeVerModule(new SafeVerModule(this))
                .build()
                .inject(this);


    }

    private void countDown() {
        disposable.add(RxUtils.countdown(60).subscribe(integer -> {
            if (integer != 0) {
                regetTV.setEnabled(false);
                regetTV.setText(Phrase.from("重新获取({count}s)").put("count", integer).format());
            } else {
                regetTV.setEnabled(true);
                regetTV.setText("重新获取");
            }
        }));
    }


    @OnClick(R.id.regetTV)
    public void onClickReget() {
        verCodePresenter.getVerCode(phone, verCode.getNumCode());
    }

    @Override
    protected boolean userAutoBindBundle() {
        return true;
    }

    @Override
    protected void gc() {
        if (disposable != null) {
            disposable.dispose();
            disposable = null;
        }
        super.gc();
    }

    @Override
    protected int layoutId() {
        return R.layout.a_input_vercode;
    }

    @Override
    public void showMessage(String msg) {

    }

    @Override
    public void onRequesrStart() {
        progressHudUtil.showProgressHud(false);
    }

    @Override
    public void onRequestFinish() {
        progressHudUtil.dismissProgressHud();
    }


    @Override
    public void onGetVerCode(VerCode verCode) {
        this.verCode = verCode;
        if (!TextUtils.isEmpty(verCode.getNumCode())) {
            EventManager.getInstance().postEvent(EventBusTag.NOTIFY_REFRESH_VERCODE);
            finish();
        } else {
            countDown();
        }
    }

    @Override
    public void onLoginSuccess(LoginInfo loginInfo) {

        if (loginInfo.getVerify().isNeedCheckQuestion()) {
            startActivity(SetOrCheckSafeVerActivityAutoBundle.builder(true).build(this));
            finish();
        } else {
            if (loginInfo.getVerify().getNeedSetCheck() == null) {
                toMain();
            } else {
                showVerDialog(loginInfo.getVerify().getNeedSetCheck());
            }
        }
    }

    private void showVerDialog(LoginVerInfo.ErrorInfo errorInfo) {

        String message = Phrase.from("您的账号于{time} 在{device}登录过,为了保障您的账号安全,请马上设置身份验证;若是本人操作,请忽略。").put("time", errorInfo.getTime())
                .put("device", TextUtils.isEmpty(errorInfo.getDeviceName()) ? "其它设备" : errorInfo.getDeviceName()).format().toString();
        AlertDialog dialog = new AlertDialog.Builder(this).setTitle("提示")
                .setMessage(message)
                .setNegativeButton("是我本人", (dialog1, which) -> {
                    safeVerPresenter.requestTrustClient(errorInfo.getId());
                })
                .setPositiveButton("设置验证", (dialog1, which) -> {

                    startActivity(SetOrCheckSafeVerActivityAutoBundle.builder(false).build(this));
                    finish();

                })
                .setCancelable(false)
                .create();
        dialog.show();


    }

    private void toMain() {

        Intent intent = new Intent(mActivity, MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void onSafeVerQuestions(List<IdAndCon> questions) {

    }

    @Override
    public void onSetSafeVerQuestion(ResponseMsg msg) {

    }

    @Override
    public void onCheckSafeVerQuestion(ResponseMsg msg) {

    }

    @Override
    public void onTrustClient(ResponseMsg msg) {
        ToastUtil.makeToast(msg.getMsg());
        Intent intent = new Intent(mActivity, MainActivity.class);
        startActivity(intent);
        finish();
    }
}
